#include <chrono>

#include "commonDefine.h"
#include "netTool.h"
#include "serial_common.h"

#include "uart.h"


serialTool::serialTool(cmdWorker* parser):
    serialFD(-1),
    worker(parser)
{

}

serialTool::~serialTool()
{
    serialClose();
}


int serialTool::serialToolInit(std::string &devName, int speed, int flow_ctrl, int databits, int stopbits, int parity)
{
    
    serialFD = HI_Serial_Open(devName.c_str());
    if (serialFD < 0)
    {
        ERRO_PRT("error HI_Serial_Open %s\n", devName.c_str());
        return -1;
    }

    if (HI_Serial_Set(serialFD, speed, flow_ctrl, databits, stopbits, parity) < 0)
    {
        HI_Serial_Close(serialFD);
        ERRO_PRT("error HI_Serial_Set %s\n", devName.c_str());
        return -1;
    }

    // add serial fd to selectHelper
    SelectHelperV2::INS().FD_SELECT(serialFD,worker);

    return serialFD;
}

int serialTool::serialSend(const char *data, int length)
{
    std::string sendStr = worker->protocalSerial(data,length);
    if(serialFD > 0 && sendStr.empty()  == false){
        return HI_Serial_Send(serialFD,sendStr.data(),sendStr.size());
    }
    return 0;
}

int serialTool::serialClose()
{
    if(serialFD > 0){
        SelectHelperV2::INS().FD_CANCEL(serialFD);
        HI_Serial_Close(serialFD);
        serialFD = -1;
    }

    return 0;
}
